<template>
  <draw-component
    :drawer-visible="state.show"
    size="410px"
    title="新增菜单"
    @close-drawer="handleClose"
    @save-drawer="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="state.formData"
      :rules="state.formRules"
      label-width="105px"
      class="my-form-box2"
      @click="state.iconShow = false"
    >
      <el-form-item v-if="state.currentId && !state.isEdit" label="上级菜单:" prop="parentPermissionName">
        <el-input v-model="state.formData.parentPermissionName" disabled></el-input>
      </el-form-item>
      <el-form-item label="菜单名称:" prop="permissionName">
        <el-input v-model="state.formData.permissionName" placeholder="请输入菜单名称"></el-input>
      </el-form-item>
      <el-form-item label="菜单类型:" prop="permissionType">
        <el-radio-group v-model="state.formData.permissionType">
          <template v-if="(state.isEdit && (!state.parentId || state.parentId == '0')) || !state.currentId">
            <el-radio label="1">应用</el-radio>
          </template>
          <template v-else>
            <el-radio v-if="state.currentId" label="2">菜单</el-radio>
            <el-radio label="3">按钮</el-radio>
          </template>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="state.formData.permissionType != '3'"
        label="数据权限限制:"
        prop="permissionDataLimit"
      >
        <el-select v-model="state.formData.permissionDataLimit" placeholder="请选择数据权限限制">
          <el-option
            v-for="item in permissionDataLimitDics"
            :key="item.code"
            :label="`${item.code} - ${item.name}`"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="展示序号:" prop="displayOrder">
        <el-input v-model="state.formData.displayOrder" placeholder="请输入序号"></el-input>
      </el-form-item>
      <el-form-item v-if="state.formData.permissionType != '3'" label="图标:" prop="permissionLogo">
        <el-popover :visible="state.iconShow" placement="bottom-start" width="350px" trigger="click">
          <icon-select ref="iconSelect" @selected="handleIconChange" />
          <template #reference>
            <el-input
              ref="iconInput"
              v-model="state.formData.permissionLogo"
              class="icon-input"
              placeholder="点击选择图标"
              readonly
              @click.stop="state.iconShow = !state.iconShow"
            >
              <template #prefix>
                <i
                  v-if="state.formData.permissionLogo"
                  class="iconfont"
                  :class="`${state.formData.permissionLogo}`"
                ></i>
              </template>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item v-if="state.formData.permissionType != '3'" label="请求路径:" prop="permissionUrl">
        <el-input v-model="state.formData.permissionUrl" placeholder="请输入请求路径"></el-input>
      </el-form-item>
      <el-form-item v-if="state.formData.permissionType != '3'" label="分组:" prop="group">
        <el-input v-model="state.formData.group" placeholder="请输入分组"></el-input>
      </el-form-item>
      <el-form-item v-if="state.formData.permissionType == '2'" label="路由:" prop="routeName">
        <el-input v-model="state.formData.routeName" placeholder="请输入路由"></el-input>
      </el-form-item>
      <el-form-item v-if="state.formData.permissionType == '3'" label="键值:" prop="permissionKey">
        <el-input v-model="state.formData.permissionKey" placeholder="请输入键值"></el-input>
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input v-model="state.formData.remark" type="textarea" placeholder="请输入备注"></el-input>
      </el-form-item>
    </el-form>
  </draw-component>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { permissionDataLimitDics } from '@/hooks/dicsData'
import { validInitNum, validPermissionKey, validMenu, validEnglish } from '@/utils/validate'
import { addSubmit, editSubmit, getMenuDetail } from '../api'
import IconSelect from './iconSelect.vue'
import { useProxy } from '@/utils/proxy'
const emit = defineEmits(['handleAdded'])
const { proxy } = useProxy()
const formRef = ref<FormInstance>()
const state = reactive({
  currentId: '',
  iconShow: false,
  parentId: '',
  isEdit: false,
  show: false,
  isSubmiting: false,
  formData: {
    parentPermissionName: '',
    permissionName: '',
    permissionType: '1',
    permissionDataLimit: '1',
    displayOrder: '',
    permissionLogo: '',
    permissionUrl: '',
    routeName: '',
    group: '',
    permissionKey: '',
    remark: ''
  },
  formRules: {
    permissionName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    permissionUrl: [{ required: true, message: '请输入请求路径', trigger: 'blur' }, { validator: validMenu }],
    group: [{ required: true, message: '请输入分组', trigger: 'blur' }, { validator: validMenu }],
    displayOrder: [
      { required: true, message: '请输入展示序号', trigger: 'blur' },
      { validator: validInitNum }
    ],
    routeName: [{ validator: validEnglish }],
    permissionKey: [
      { required: true, message: '请输入键值', trigger: 'blur' },
      { validator: validPermissionKey }
    ]
  } as FormRules
})

// 关闭回调
const handleClose = () => {
  state.show = false
  state.currentId = ''
  state.parentId = ''
  state.isEdit = false
  state.formData = {
    parentPermissionName: '',
    permissionName: '',
    permissionType: '1',
    permissionDataLimit: '1',
    displayOrder: '',
    permissionLogo: '',
    permissionUrl: '',
    routeName: '',
    group: '',
    permissionKey: '',
    remark: ''
  }
}
// 选图标回调
const handleIconChange = (name: string) => {
  state.formData.permissionLogo = name
  state.iconShow = false
}
// 获取详情
const getDetail = async () => {
  let { data } = await getMenuDetail<any>(state.currentId)
  const form = {} as any
  Object.keys(state.formData).forEach((item, index) => {
    form[item] = data[item] ?? ''
  })
  state.formData = form
}
// 保存
const handleSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      if (state.isSubmiting) return
      state.isSubmiting = true
      const params = { ...state.formData } as any
      delete params.parentPermissionName
      if (state.isEdit) {
        editSubmit(state.currentId, params)
          .then(() => {
            proxy.$message.msgSuccess('编辑成功')
            state.isSubmiting = false
            handleClose()
            emit('handleAdded')
          })
          .catch(() => {
            state.isSubmiting = false
          })
      } else {
        params.parentPermissionId = state.currentId
        addSubmit(params)
          .then(() => {
            proxy.$message.msgSuccess('新增成功')
            state.isSubmiting = false
            handleClose()
            emit('handleAdded')
          })
          .catch(() => {
            state.isSubmiting = false
          })
      }
    }
  })
}
defineExpose({ state, getDetail })
</script>

<style lang="scss" scoped>
.icon-input {
  :deep(.el-input__prefix) {
    color: #333;
  }
}
</style>
